import { useBox } from "@react-three/cannon";
import * as textures from "../images/textures";
import { useStore } from "../hooks/useStore";

export const Cube = ({ position, texture }) => {
  const activeTexture = textures[texture + "Texture"];
  // console.log(activeTexture);
  const [addCube, removeCube] = useStore((state) => [
    state.addCube,
    state.removeCube,
  ]);
  // 获取当前视角模式
  const isThirdPerson = useStore(state => state.isThirdPerson);
  
  activeTexture.repeat.set(0.5, 0.5);
  const [ref] = useBox(() => {
    return {
      type: "Static",
      position,
    };
  });
  return (
    <mesh
      ref={ref}
      onClick={(e) => {
        // 在第三人称模式下，不处理点击事件，由Player组件中的射线检测处理
        if (isThirdPerson) {
          return;
        }
        
        e.stopPropagation();
        const clickedFace = Math.floor(e.faceIndex / 2);
        const { x, y, z } = ref.current.position;
        
        if (e.button===2) {
          removeCube(x, y, z);
          return;
        } else if (clickedFace === 0) {
          addCube(x + 1, y, z);
          return;
        } else if (clickedFace === 1) {
          addCube(x - 1, y, z);
          return;
        } else if (clickedFace === 2) {
          addCube(x, y + 1, z);
          return;
        } else if (clickedFace === 3) {
          addCube(x, y - 1, z);
          return;
        } else if (clickedFace === 4) {
          addCube(x, y, z + 1);
          return;
        } else if (clickedFace === 5) {
          addCube(x, y, z - 1);
          return;
        }
      }}
    >
      <boxGeometry attach="geometry" />
      <meshStandardMaterial attach="material" map={activeTexture} />
    </mesh>
  );
};
